const fs = require("fs");

/**
 * 读取ASS文件内容
 * @param {string} filePath - ASS文件路径
 * @returns {object} 包含文件头、样式和事件内容的对象
 */
function readAssFile(filePath) {
  const content = fs.readFileSync(filePath, "utf8");
  const lines = content.split("\n");

  const result = {
    header: [],
    styles: [],
    events: [],
  };

  let currentSection = "header";

  for (const line of lines) {
    const trimmedLine = line.trim();

    if (trimmedLine === "[Script Info]") {
      currentSection = "header";
      result.header.push(line);
    } else if (trimmedLine === "[V4+ Styles]") {
      currentSection = "styles";
      result.styles.push(line);
    } else if (trimmedLine === "[Events]") {
      currentSection = "events";
      result.events.push(line);
    } else {
      if (currentSection === "header") {
        result.header.push(line);
      } else if (currentSection === "styles") {
        result.styles.push(line);
      } else if (currentSection === "events") {
        result.events.push(line);
      }
    }
  }

  return result;
}

/**
 * 合并两个ASS文件
 * @param {string} mainAssFile - 主字幕文件路径
 * @param {string} wordAssFile - 单词字幕文件路径
 * @param {string} outputFile - 输出文件路径
 */
function mergeAssFiles(mainAssFile, wordAssFile, outputFile) {
  // 读取两个ASS文件
  const mainAss = readAssFile(mainAssFile);
  const wordAss = readAssFile(wordAssFile);

  // 合并文件头（使用主字幕的文件头）
  const mergedHeader = mainAss.header;

  // 合并样式部分（合并两个文件的样式）
  const mergedStyles = [...mainAss.styles];

  // 从wordAss中提取样式行（排除标题行）
  const wordStyleLines = wordAss.styles.filter(line => line.startsWith("Style:"));
  mergedStyles.push(...wordStyleLines);

  // 合并事件部分（合并两个文件的事件）
  const mergedEvents = [...mainAss.events];

  // 从wordAss中提取对话行（排除格式行）
  const wordEventLines = wordAss.events.filter(line => line.startsWith("Dialogue:"));
  mergedEvents.push(...wordEventLines);

  // 组合最终内容
  const mergedContent = [...mergedHeader, "", ...mergedStyles, "", ...mergedEvents].join("\n");

  // 写入合并后的文件
  fs.writeFileSync(outputFile, mergedContent, "utf8");

  console.log(`  成功合并ASS文件: ${mainAssFile} + ${wordAssFile} -> ${outputFile}`);
}

/**
 * 合并两个ASS文件，确保单词字幕样式优先
 * @param {string} mainAssFile - 主字幕文件路径
 * @param {string} wordAssFile - 单词字幕文件路径
 * @param {string} outputFile - 输出文件路径
 */
function mergeAssFilesWithWordPriority(mainAssFile, wordAssFile, outputFile) {
  // 读取两个ASS文件
  const mainAss = readAssFile(mainAssFile);
  const wordAss = readAssFile(wordAssFile);

  // 合并文件头（使用主字幕的文件头）
  const mergedHeader = mainAss.header;

  // 合并样式部分（确保单词字幕样式不被覆盖）
  // 首先提取主字幕样式
  const mainStyleLines = mainAss.styles.filter(line => line.startsWith("Style:"));

  // 提取单词字幕样式
  const wordStyleLines = wordAss.styles.filter(line => line.startsWith("Style:"));

  // 获取单词字幕样式名称，避免冲突
  const wordStyleNames = wordStyleLines.map(line => {
    const parts = line.split(",");
    return parts[0].substring(6); // 去掉 "Style:" 前缀
  });

  // 过滤主字幕样式，移除与单词字幕同名的样式
  const filteredMainStyles = mainStyleLines.filter(line => {
    const parts = line.split(",");
    const styleName = parts[0].substring(6); // 去掉 "Style:" 前缀
    return !wordStyleNames.includes(styleName);
  });

  // 合并样式，单词字幕样式优先
  const mergedStyles = [
    "[V4+ Styles]",
    "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
    ...filteredMainStyles,
    ...wordStyleLines,
  ];

  // 合并事件部分（合并两个文件的事件）
  const mergedEvents = [...mainAss.events];

  // 从wordAss中提取对话行（排除格式行）
  const wordEventLines = wordAss.events.filter(line => line.startsWith("Dialogue:"));
  mergedEvents.push(...wordEventLines);

  // 组合最终内容
  const mergedContent = [...mergedHeader, "", ...mergedStyles, "", ...mergedEvents].join("\n");

  // 写入合并后的文件
  fs.writeFileSync(outputFile, mergedContent, "utf8");

  console.log(`  成功合并ASS文件(单词样式优先): ${mainAssFile} + ${wordAssFile} -> ${outputFile}`);
}

module.exports = {
  mergeAssFiles,
  mergeAssFilesWithWordPriority,
};
